package com.zy.qudadid.ui.activity;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.zy.lcpassenger.R;
import com.zy.qudadid.network.Const;
import com.zy.qudadid.presenter.RegisterPresenter;
import com.zy.qudadid.ui.activity.base.ToolBarActivity;
import com.zy.qudadid.ui.view.RegisterView;
import com.zy.qudadid.utils.AESCrypt;
import com.zy.qudadid.utils.StringUtil;
import com.zy.qudadid.utils.TextUtil;
import com.zy.qudadid.utils.ToolsUtil;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

/**
 * Created by ASUS on 2017/2/15.
 */

public class RegisterActivity extends ToolBarActivity<RegisterPresenter> implements RegisterView {

    private final String TAG = "RegisterActivity";

    @Bind(R.id.btn_confirm)
    Button btn_confirm;
    @Bind(R.id.btn_signin_code)
    TextView btn_signin_code;
    @Bind(R.id.et_tel)
    EditText et_tel;
    @Bind(R.id.et_code)
    EditText et_code;
    @Bind(R.id.et_password)
    EditText et_password;
    @Bind(R.id.et_password2)
    EditText et_password2;

    @Override
    protected CharSequence provideTitle() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_register;
    }

    @Override
    public void initListeners() {

    }

    @Override
    public RegisterPresenter createPresenter() {
        return new RegisterPresenter();
    }

    @Override
    protected void initThings(Bundle savedInstanceState) {
        //  super.initThings(savedInstanceState);

        time = new TimeCount(60000, 1000);

        // 短信验证
        // 初始化短信验证
        SMSSDK.initSDK(this, Const.APPKEY, Const.APPSECRET);
        EventHandler eh = new EventHandler() {

            @Override
            public void afterEvent(int event, int result, Object data) {
                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                handlersms.sendMessage(msg);
            }
        };
        SMSSDK.registerEventHandler(eh); // 注册短信回调
    }

    /**
     * 创建可调用ui的handler
     */
    Handler handlersms = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int event = msg.arg1;
            int result = msg.arg2;
            Object data = msg.obj;

            if (result == SMSSDK.RESULT_COMPLETE) {
                // 回调完成
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    // 提交验证码验证成功

                    String phoneNumber = et_tel.getText().toString();//获取UI上的填的注册信息、调注册接口
                    String pass = et_password.getText().toString();


                    //           toast("提交验证码验证成功,调注册接口");

                    Map map = new HashMap();
                    map.put("tel", phoneNumber);
//                    map.put("lng", lng);
//                    map.put("lat", lat);
                    map.put("type", 1);
                    map.put("pwd", pass);
                    map.put("username", phoneNumber);
                    String json = StringUtil.toJson(map);
                    try {
                        String data1 = AESCrypt.getInstance().encrypt(json);
                        String d = StringUtil.replaceBlank(data1);
                        presenter.Register(d);
                    } catch (Exception ex) {
                    }
//                    finish();
                } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                    // 获取验证码成功
                    time.start();//开始计时
                    toast("发送成功");
                } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                    // 返回支持发送验证码的国家列表
                }
            } else {
//                try {
//                    snb(event == SMSSDK.EVENT_GET_VERIFICATION_CODE ? "验证过于频繁，请稍后再试" : "验证码错误",btn_signin_code);
//                }catch (Exception ex){}

                try {
                    //根据服务器返回的网络错误，给toast提示
                    JSONObject object = new JSONObject(((Throwable) data).getMessage());
                    String des = object.optString("detail");//错误描述
                    int status = object.optInt("status");//错误代码
                    if (status > 0 && !TextUtils.isEmpty(des)) {
                        toast(des);
                    }
                } catch (Exception e) {
                    toast("发送新验证码失败，请稍后再试！");
                }
            }
        }
    };


    /**
     * 获取验证码倒计时
     */
    private TimeCount time;

    @Override
    public void registerSuccess() {
        toast("注册成功");
    }

    @Override
    public void registerError(String msg) {
        toast(msg);
    }

    @Override
    public void exception() {
//        toast("注册失败");
        ToolsUtil.print(TAG, "注册失败");
    }

    @Override
    public void loginSuccess() {
        ToolsUtil.print(TAG, "注册成功");
    }

    @Override
    public void loginError(String msg) {
        ToolsUtil.print(TAG, "注册失败：" + msg);
    }

    //获取验证码的时候避免重复点击
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {// 计时完毕
            btn_signin_code.setText("重新获取验证码");
            btn_signin_code.setClickable(true);
//            btnGetVerifyCode.setEnabled(true);
            //       btn_signin_code.setBackgroundResource(R.drawable.border_green_4dp);
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程
            btn_signin_code.setClickable(false);//防止重复点击
//            btnGetVerifyCode.setEnabled(false);
//            btnGetVerifyCode.setBackgroundResource(R.drawable.border_gray_4dp);
            btn_signin_code.setText(millisUntilFinished / 1000 + "s后可重发");
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterAllEventHandler();
    }


    @OnClick({R.id.btn_signin_code, R.id.btn_confirm})
    protected void button(View view) {
        String username = et_tel.getText().toString().trim();
        switch (view.getId()) {
            case R.id.btn_signin_code:
                /*获取验证码*/
                sendMessageCode(username);
                break;
            case R.id.btn_confirm:
                /*确认_核对信息完整度、核对两次密码是否正确、提交验证码验证*/
                String code = et_code.getText().toString().trim();
                String password = et_password.getText().toString().trim();
                String repassword = et_password2.getText().toString().trim();


                validDate(username, code, password, repassword);


//                String phoneNumber = et_tel.getText().toString();//获取UI上的填的注册信息、调注册接口
//                String pass = et_password.getText().toString();
//
//                Map map = new HashMap();
//                map.put("tel", phoneNumber);
//                map.put("type", 1);
//                map.put("pwd", pass);
//                map.put("username", phoneNumber);
//                String json = StringUtil.toJson(map);
//                try {
//                    String data1 = AESCrypt.getInstance().encrypt(json);
//                    String d = StringUtil.replaceBlank(data1);
//                    presenter.Register(d);
//                } catch (Exception ex) {
//                }


                break;
        }
    }


    /**
     * 检查手机格式、获取验证码
     */
    public void sendMessageCode(String username) {
        if (StringUtil.isEmpty(username)) {
            toast("手机号不能为空!");
        } else if (!TextUtil.isMobile(username)) {
            toast("手机号格式无效!");
        } else {
            SMSSDK.getVerificationCode("86", username);//获取验证码
            //   view.verification();
        }
    }

    /**
     * 确认_核对信息完整度、核对两次密码是否正确、提交验证码验证
     */
    public void validDate(String username, String code, String password, String repassword) {
        if (StringUtil.isEmpty(username)) {
            toast("手机号不能为空!");
        } else if (!TextUtil.isMobile(username)) {
            toast("手机号格式无效!");
        } else if (code.length() != 4) {
            toast("验证码格式无效!");
        } else if (StringUtil.isEmpty(password)) {
            toast("密码不能为空!");
        } else if (!password.equals(repassword)) {
            toast("两次密码不一致!");
        } else if (password.length() < 6) {
            toast("密码长度不能少于6位!");
        } else {
            SMSSDK.submitVerificationCode("86", username, code);//提交验证码验证
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        time.cancel();
        return super.onKeyDown(keyCode, event);
    }
}
